<template>
  <k-view class="rank-page">
    <top-banner :title="pageTitle" :subTitle="pageSubTitle"></top-banner>
    <page-tabs
      :isRank="true"
      :modelValue="activeTab"
      :tabList="tabList"
      @change="handleTabChange"
    ></page-tabs>
    <k-view class="content-view">
      <rank-table
        :data="data"
        :requestData="tableData"
        :globalLoading="isLoading"
        :isShowNoData="isEmpty"
        @click-row="clickRow"
        @tableSort="tableSort"
        @toBottom="toBottomThrottle"
        :customSort="customSort"
        :themeType="'mobile-app-' + theme"
      ></rank-table>
    </k-view>
  </k-view>
</template>

<script>
import topBanner from '../../components/Home/topBanner.vue';
import pageTabs from '../../components/Home/pageTabs.vue';
import { getBlockRankingList, getRankingList } from '@/apis';
import Apis from '@king-fisher/apis';
import {
  changeStringIntoDate,
  getCurrentDate,
  getUrlSearch,
  jumpByUrl,
  jumpToFenshi,
  setCookie,
} from '@/utils';
import { tableHeaderData } from '@/config/tableHeader';
import { sendClickStat, sendOnceStat, sendPageStat } from '@/utils/stat';
import { INDEX_TAB_ID, PAGEID } from '@/config/stat';
import { debounce, throttle } from '../../utils/index';
import themeMixin from '../../mixins/themeMixin';
import rankReload from '@/components/Home/rankReload.vue';
import { getNativeSelfCodeList } from '@/utils/selfCode';

export default {
  components: {
    topBanner,
    pageTabs,
    rankReload,
  },
  data() {
    return {
      text: '表格',
      activeTab: 1,
      pageTitle: '健康指数排行榜',
      data: tableHeaderData,
      pageSubTitle: '更新时间： ',
      tableData: [],
      originData: [],
      customSort: true,
      page_size: '20',
      page_num: '0',
      sort_field: 'composite_score',
      sort_way: 'desc',
      selfCodeList: [],
      lastParams: '',
      lastapi: '',
      isLoading: false,
      validSelfCodeList: [],
      stockCodes: '',
    };
  },
  mixins: [themeMixin],
  computed: {
    blockType() {
      const blockTypeMap = {
        1: 'all_market',
        2: 'stock',
        3: 'industry',
        default: 'region',
      };
      return blockTypeMap[this.activeTab] || blockTypeMap.default;
    },
    tabList() {
      return [
        {
          id: 1,
          name: '全部',
          index: 1,
          show: true,
        },
        {
          id: 2,
          name: '自选',
          index: 2,
          show: this.validSelfCodeList?.length > 4,
        },
        {
          id: 3,
          name: '行业',
          index: 3,
          show: true,
        },
        {
          id: 4,
          name: '地区',
          index: 4,
          show: true,
        },
      ];
    },
    isEmpty() {
      return this.tableData.length === 0;
    },
  },
  methods: {
    handleTabChange(current) {
      // 只有此处才是点击切换页面tab
      if (this.activeTab === current) {
        return;
      } else {
        //初始化,page
        this.page_num = '0';
        this.isLoading = true;
        sendClickStat(`${PAGEID.RANK}.tab.${INDEX_TAB_ID[current]}.click`);
        this.tableData = [];
        this.originData = [];
        this.activeTab = current;
        const params: rank_params = {
          block_type: this.blockType,
          page_size: this.page_size,
          page_num: this.page_num,
          sort_field: this.sort_field,
          sort_mod: this.sort_way,
        };
        if (this.activeTab === 1) {
          tableHeaderData[1].label = '股票名称';
          this.getRankingListData(params);
        } else if (this.activeTab === 2) {
          tableHeaderData[1].label = '股票名称';
          params.stock_codes = this.stockCodes;
          this.getRankingListData(params);
        } else if (this.activeTab === 3) {
          //行业Tab，调用板块排行榜
          this.getBlockRankingListData(params);
          tableHeaderData[1].label = '行业名称';
        } else if (this.activeTab === 4) {
          //板块Tab，调用板块排行榜
          this.getBlockRankingListData(params);
          tableHeaderData[1].label = '地区名称';
        }
      }
    },
    getRankingData: debounce(async function (params, api, reload) {
      let timer;
      let realParams;
      let realApi;
      const timeout = new Promise((resolve, reject) => {
        timer = setTimeout(() => {
          reject('请求超时!');
        }, 5000);
      });
      if (reload) {
        realApi = this.lastapi;
        realParams = this.lastParams;
      } else {
        realApi = api;
        realParams = params;
      }
      Promise.race([timeout, realApi(realParams)])
        .then(res => {
          if (res.status_code !== 0) {
            Apis.Toast.show('暂未查询到相关信息');
            return;
          }
          const dataList = res.data?.list || [];
          this.tableData = this.tableData.concat(
            dataList.map(item => {
              return {
                stock_name: item.name,
                stock_code: item.code,
                composite_score: item.composite_score.toFixed(2),
                nervous_score: item.nervous_score.toFixed(2),
                motor_score: item.motor_score.toFixed(2),
                secretion_score: item.secretion_score.toFixed(2),
                immune_score: item.immune_score.toFixed(2),
                respiratory_score: item.respiratory_score.toFixed(2),
                circulatory_score: item.circulatory_score.toFixed(2),
                urinary_score: item.urinary_score.toFixed(2),
                digesive_score: item.digesive_score.toFixed(2),
                reproductive_score: item.reproductive_score.toFixed(2),
                market: item.market,
              };
            })
          );
          if (this.activeTab === 2) {
            this.pageSubTitle = `更新时间：${getCurrentDate()}`;
          } else {
            this.pageSubTitle = `更新时间：${changeStringIntoDate(res.data?.report_date)}`;
          }
          this.originData = this.originData.concat(dataList);
          if (dataList.length != 0) {
            this.page_num = String(Number(this.page_num) + 1); //每次滚动page_num+1
          }
        })
        .finally(() => {
          this.isLoading = false;
          this.lastParams = realParams;
          this.lastapi = realApi;
          clearTimeout(timer);
        });
    }, 100),
    async getRankingListData(params) {
      this.getRankingData(params, getRankingList);
    },
    async getBlockRankingListData(params) {
      this.getRankingData(params, getBlockRankingList);
    },
    getRankingListOverview() {
      this.isLoading = true;
      const params: rank_params = {
        block_type: this.blockType,
        page_size: this.page_size,
        page_num: this.page_num,
        sort_field: this.sort_field,
        sort_mod: this.sort_way,
      };
      if (this.activeTab === 2 || this.activeTab === 1) {
        params.stock_codes = this.stockCodes;
        this.getRankingListData(params);
      } else if (this.activeTab === 3 || this.activeTab === 4) {
        this.getBlockRankingListData(params);
      }
    },
    clickRow(row, column) {
      const stockIndex: number = this.originData.findIndex(item => item.code === row.stock_code);
      if (stockIndex !== -1) {
        const stockItem = this.originData[stockIndex];
        if (this.activeTab === 3 || this.activeTab === 4) {
          //行业或地区
          sendClickStat(
            `${PAGEID.RANK}.${INDEX_TAB_ID[this.activeTab]}.bmidetails.${row.stock_code}.${
              stockIndex + 1
            }.click`
          );
          jumpByUrl({
            name: 'regionrank',
            query: {
              block_code: row.stock_code,
              block_type: this.blockType,
              block_name: row.stock_name,
            },
          });
        } else {
          if (column.type === 'stock') {
            //跳转个股分时
            sendClickStat(
              `${PAGEID.RANK}.${INDEX_TAB_ID[this.activeTab]}.stocks.${row.stock_code}.${
                stockIndex + 1
              }.click`
            );
            jumpToFenshi(row.stock_code, stockItem.market, stockItem.name);
          } else {
            //跳转个股诊断
            sendClickStat(
              `${PAGEID.RANK}.${INDEX_TAB_ID[this.activeTab]}.bmidetails.${row.stock_code}.${
                stockIndex + 1
              }.click`
            );
            jumpByUrl({
              name: 'stock',
              query: {
                stockCode: row.stock_code,
                market: stockItem.market,
                stockName: row.stock_name,
              },
            });
          }
        }
      }
    },
    tableSort(key, sortWay) {
      //初始化,page
      this.page_num = '0';
      this.isLoading = true;
      this.tableData = [];
      this.originData = [];
      const params: rank_params = {
        block_type: this.blockType,
        page_size: this.page_size,
        page_num: this.page_num,
        sort_field: key,
        sort_mod: sortWay,
      };
      if (this.activeTab === 1) {
        this.getRankingListData(params);
      } else if (this.activeTab === 2) {
        params.stock_codes = this.stockCodes;
        this.getRankingListData(params);
      } else if (this.activeTab === 3) {
        this.getBlockRankingListData(params);
      } else if (this.activeTab === 4) {
        this.getBlockRankingListData(params);
      }
      this.sort_field = key;
      this.sort_way = sortWay;
    },
    toBottom() {
      const params: rank_params = {
        block_type: this.blockType,
        page_size: this.page_size,
        page_num: this.page_num,
        sort_field: this.sort_field,
        sort_mod: this.sort_way,
      };
      if (this.activeTab === 1) {
        this.getRankingListData(params);
      } else if (this.activeTab === 2) {
        params.stock_codes = this.stockCodes;
        this.getRankingListData(params);
      } else if (this.activeTab === 3) {
        this.getBlockRankingListData(params);
      } else if (this.activeTab === 4) {
        this.getBlockRankingListData(params);
      }
    },
    //拿到selfCodeList之后再去请求rankingList有多少条数据，才判断
    async getSelfCodeList() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await getNativeSelfCodeList();
          if (res && res.selfCodeList) {
            this.selfCodeList = res.selfCodeList;
            const codeList = res.selfCodeList.map(item => {
              return item.stockcode;
            });
            const params = {
              block_type: 'stock',
              page_size: '20',
              page_num: '0',
              sort_field: 'composite_score',
              sort_mod: 'desc',
              stock_codes: codeList.join(','),
            };
            this.stockCodes = codeList.join(',');
            const rankingRes = await getRankingList(params);
            if (rankingRes.status_code !== 0) {
              Apis.Toast.show('暂未查询到自选信息!');
              return;
            }
            const dataList = rankingRes.data?.list || []; //能够查到的codeList
            this.validSelfCodeList = dataList;
            resolve();
          } else {
            Apis.Toast.show('暂未查询到自选信息!');
            reject();
          }
        } catch (error) {
          Apis.Toast.show('暂未查询到自选信息!');
          reject();
        }
      });
    },
    reload() {
      this.isLoading = true;
      this.getRankingData(null, null, true);
    },
    initSelfCodeList() {
      this.getSelfCodeList().then(res => {
        if (this.validSelfCodeList.length >= 4) {
          sendOnceStat(`${PAGEID.RANK}.tab.zixuan.show`);
          if (this.activeTab == 2) {
            this.pageSubTitle = `更新时间：${getCurrentDate()}`;
            this.tableData = this.validSelfCodeList.map(item => {
              return {
                stock_name: item.name,
                stock_code: item.code,
                composite_score: item.composite_score.toFixed(2),
                nervous_score: item.nervous_score.toFixed(2),
                motor_score: item.motor_score.toFixed(2),
                secretion_score: item.secretion_score.toFixed(2),
                immune_score: item.immune_score.toFixed(2),
                respiratory_score: item.respiratory_score.toFixed(2),
                circulatory_score: item.circulatory_score.toFixed(2),
                urinary_score: item.urinary_score.toFixed(2),
                digesive_score: item.digesive_score.toFixed(2),
                reproductive_score: item.reproductive_score.toFixed(2),
                market: item.market,
              };
            });
          }
        }
      });
    },
  },

  created() {
    const query = getUrlSearch();
    if (query && query.activeTab) {
      this.activeTab = Number(query.activeTab);
    }
    // 非自选tab下直接调用接口
    if (this.activeTab !== 2) {
      this.getRankingListOverview();
    }
    //自选tab下先获取自选股列表，再调用接口
    this.initSelfCodeList();
    this.toBottomThrottle = throttle(this.toBottom, 1000);
  },
  mounted() {
    setCookie().then(id => {
      sessionStorage.setItem('userIdKey', id);
      sendPageStat(`${PAGEID.RANK}`);
    });
  },
};
</script>

<style lang="less">
.rank-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .content-view {
    width: 100%;
    height: 100%;
  }
}

[theme-mode='black'] {
  .rank-page {
    background-color: #1c1c1c;

    .content-view {
      background-color: #1c1c1c;
    }
  }
}
.hxm-table {
  z-index: 0 !important;
}
</style>
